﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Media;
using System.Globalization;

namespace Helper_Ji
{
    class Helper_Convert
    {
     
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// 返回处理后的十六进制字符串 
        /// </summary>
        /// <param name="mStr"></param>
        /// <returns></returns>
        public string StrToHex(string mStr)
        {
            return BitConverter.ToString(
            ASCIIEncoding.Default.GetBytes(mStr)).Replace("-", " ");
        }

        /// <summary>
        /// 返回十六进制代表的字符串
        /// </summary>
        /// <param name="mHex"></param>
        /// <returns></returns>
        public string HexToStr(string mHex)
        {
            mHex = mHex.Replace(" ", "");
            if (mHex.Length <= 0) return "";
            byte[] vBytes = new byte[mHex.Length / 2];
            for (int i = 0; i < mHex.Length; i += 2)
                if (!byte.TryParse(mHex.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2]))
                    vBytes[i / 2] = 0;
            return ASCIIEncoding.Default.GetString(vBytes);
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, System.Text.Encoding charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("/n", "");
            hex = hex.Replace("//", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            return charset.GetString(bytes);
        }

       
       /// <summary>
       /// BitMap To ImageSource
       /// </summary>
       /// <param name="bitmap"></param>
       /// <returns></returns>
        public static ImageSource BmpToImgSourISC(System.Drawing.Bitmap bitmap)
        {
            ImageBrush imageBrush = new ImageBrush();
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(stream);
            }
            return imageBrush.ImageSource;
        }

        /// <summary>
        /// BitMap To ImageSource
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static ImageSource BmpToImgSourBI(System.Drawing.Bitmap bitmap)
        {
            BitmapImage image = new BitmapImage();
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                image.StreamSource = stream;
            }
            return image;
        }

        /// <summary>
        /// 文字保存成Control.Image
        /// </summary>
        /// <param name="textToFormat"></param>
        /// <param name="culture"></param>
        /// <param name="flowDirection"></param>
        /// <param name="typeface"></param>
        /// <param name="emSize"></param>
        /// <param name="foreground"></param>
        /// <param name="numberSubstitution"></param>
        /// <param name="textFormattingMode"></param>
        /// <returns></returns>
        public static System.Windows.Controls.Image TextToImage(string textToFormat, CultureInfo culture, System.Windows.FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground )
        {
            System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
            FormattedText textTemp = new FormattedText(textToFormat, culture, flowDirection, typeface, emSize, foreground);
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            drawingContext.DrawText(textTemp, new System.Windows.Point(2, 2));
            drawingContext.Close();
            RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);
            myImage.Source = bmp;
            return myImage;
        }

        public static System.Windows.Controls.Image TextToImage(string textToFormat, CultureInfo culture, System.Windows.FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground, NumberSubstitution numberSubstitution)
        {
            System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
            FormattedText textTemp = new FormattedText(textToFormat, culture, flowDirection, typeface, emSize, foreground, numberSubstitution);
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            drawingContext.DrawText(textTemp, new System.Windows.Point(2, 2));
            drawingContext.Close();
            RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);
            myImage.Source = bmp;
            return myImage;
        }
        
        public static System.Windows.Controls.Image TextToImage(string textToFormat, CultureInfo culture, System.Windows.FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground, NumberSubstitution numberSubstitution, TextFormattingMode textFormattingMode)
        {
            System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
            FormattedText textTemp = new FormattedText(textToFormat, culture, flowDirection, typeface, emSize, foreground, numberSubstitution, textFormattingMode);
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            drawingContext.DrawText(textTemp, new System.Windows.Point(2, 2));
            drawingContext.Close();
            RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);
            myImage.Source = bmp;
            return  myImage;
        }


        /// <summary>
        /// 创建Image控件
        /// </summary>
        /// <param name="imageSource"></param>
        /// <returns></returns>
        public static System.Windows.Controls.Image CreatImage(ImageSource imageSource)
        {
            System.Windows.Controls.Image image = new System.Windows.Controls.Image();
            image.Source = imageSource;
            image.Stretch = System.Windows.Media.Stretch.Fill;
            return image;
        }
    }
}
